package app.controllers.admin.ktv;

import app.Const;
import app.models.DaoKit;
import app.models.booking.KtvProject;
import app.models.brand.Brand;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;

/**
 * <p>
 * KTV预定
 * </p>
 *
 * @author liuhui
 * @version 1.0 14-5-24 下午4:06
 */
public class KtvController extends BasicController {
    public void index() {
        render("index.ftl");
    }

    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        String name = getPara("name");
        Page<KtvProject> pageRt = KtvProject.dao.datatable(criterias, name);

        renderDataTables(pageRt, criterias);
    }

    public void create() {
        KtvProject ktvProject = new KtvProject();
        setAttr("ktv", ktvProject);
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);

        setBrands();

        render("item.ftl");
    }

    private void setBrands() {
        setAttr("brands", Brand.dao.findByCatetory(Const.KTV));
    }

    public void edit() {
        setBrands();
        KtvProject ktvProject = KtvProject.dao.findById(getPara());
        String pictures = ktvProject.getStr("picture");
        if (!Strings.isNullOrEmpty(pictures)) {
            final List<String> pics = AppFunc.COMMA_SPLITTER.splitToList(pictures);
            setAttr("pics", pics);
        }
        setAttr("ktv", ktvProject);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        render("item.ftl");

    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("ktv.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

    public void save() {
        KtvProject ktv = getModel(KtvProject.class, "ktv");
        if (DaoKit.isNew(ktv)) {
            ktv.set("create_time", DateProvider.DEFAULT.getCurrentDate());
            ktv.save();
        } else {
            ktv.update();
        }
        redirect("/admin/ktv/ktv");
    }


}
